package server

import (
	"net/http"
	"ywebgo/filter"
	"ywebgo/handler"
)

type Server interface {
	handler.Registry
	Start(addr string) error
	AddFilter(build filter.Builder)
}

type StubServer struct {
	handler handler.Handler
	filter  filter.Filter
}

func (s *StubServer) Enroll(method string, pattern string, handlerFunc handler.HandleFunc) {
	s.handler.Enroll(method, pattern, handlerFunc)
}

func (s *StubServer) Start(addr string) error {
	return http.ListenAndServe(addr, s)
}

var _ http.Handler = &StubServer{}

func (s *StubServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.filter(w, r)
}

func (s *StubServer) AddFilter(build filter.Builder) {
	s.filter = build(s.filter)
}

func NewServer() Server {
	trieHandler := handler.NewTrieHandler()
	return &StubServer{
		//handler: handler.NewMapHandler(),
		handler: trieHandler,
		filter:  trieHandler.Handle,
	}
}
